package cn.huapu.power.energy.util;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author jzx
 * @title: PasswordEncoderMessageDigest
 * @projectName jzx
 * @description: TODO Md5加密工具类
 * @date 2019-5-2311:06
 */
public class PasswordEncoderMessageDigest {
    private static final char[] HEX_DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
            'd', 'e', 'f'};
    private String encodingAlgorithm;
    private String characterEncoding;

    public PasswordEncoderMessageDigest() {
        this("MD5");
    }

    public PasswordEncoderMessageDigest(String encodingAlgorithm) {
        this.encodingAlgorithm = encodingAlgorithm;
    }

    public String encode(String password) {
        if (password == null) {
            return null;
        } else {
            try {
                if (this.encodingAlgorithm != null && this.encodingAlgorithm.trim().length() != 0
                        && !this.encodingAlgorithm.equalsIgnoreCase("none")) {
                    MessageDigest messageDigest = MessageDigest.getInstance(this.encodingAlgorithm);
                    if (this.characterEncoding != null && this.characterEncoding.length() > 0) {
                        messageDigest.update(password.getBytes(this.characterEncoding));
                    } else {
                        messageDigest.update(password.getBytes());
                    }

                    byte[] digest = messageDigest.digest();
                    return this.getFormattedText(digest);
                } else {
                    return password;
                }
            } catch (NoSuchAlgorithmException var4) {
                throw new SecurityException(var4);
            } catch (UnsupportedEncodingException var5) {
                throw new RuntimeException(var5);
            }
        }
    }

    private String getFormattedText(byte[] bytes) {
        StringBuilder buf = new StringBuilder(bytes.length * 2);

        for (int j = 0; j < bytes.length; ++j) {
            buf.append(HEX_DIGITS[bytes[j] >> 4 & 15]);
            buf.append(HEX_DIGITS[bytes[j] & 15]);
        }

        return buf.toString();
    }

    public String getEncodingAlgorithm() {
        return this.encodingAlgorithm;
    }

    public String getCharacterEncoding() {
        return this.characterEncoding;
    }

    public void setCharacterEncoding(String characterEncoding) {
        this.characterEncoding = characterEncoding;
    }

    public void setEncodingAlgorithm(String encodingAlgorithm) {
        this.encodingAlgorithm = encodingAlgorithm;
    }

    public static void main(String[] args) {
    }
}
